import React from 'react';
import { View, Text } from 'react-native';
import moment from 'moment';
import styles from './styles';

const S = 1000;
const M = 60 * S;
const H = 60 * M;
const D = 24 * H;

export default class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      now: moment()
    };
  }
  timer;
  componentDidMount() {
    if (this.props.date) {
      this.timer = setInterval(() => {
        this.setState({
          now: moment()
        });
      }, S);
    }
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  render() {
    const diff = moment(this.props.date).diff(this.state.now);
    if (diff < 0) {
      return (
        <View style={[{ backgroundColor: '#ff3333' }, styles.wrap]}>
          <Text style={styles.text}>已超时</Text>
        </View>
      );
    }
    const day = Math.floor(diff / D);
    const dayLast = diff % D;
    const hour = Math.floor(dayLast / H);
    const hourLast = diff % H;
    const minute = Math.floor(hourLast / M);
    const minuteLast = diff % M;
    const second = Math.floor(minuteLast / S);
    return (
      <View style={[{backgroundColor: '#00b33c'}, styles.wrap]}>
        <Text style={styles.text}>剩</Text>
        <Text style={styles.text}>{day}</Text>
        <Text style={styles.text}>天</Text>
        <Text style={styles.text}>{hour}</Text>
        <Text style={styles.text}>时</Text>
        <Text style={styles.text}>{minute}</Text>
        <Text style={styles.text}>分</Text>
        <Text style={styles.text}>{second}</Text>
        <Text style={styles.text}>秒</Text>
      </View>
    );
  }
}
